<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      :width="dialogWidth"
      destroy-on-close
      append-to-body
    >
      <el-form
        :model="formData"
        size="small"
        label-width="80px"
        ref="form"
        v-if="taskData != null"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务内容" prop="cate">
              {{ taskData.taskContent }}
              <el-button type="text">导出任务卡</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="taskData.taskAttaches.length > 0">
          <el-col :span="12">
            <el-form-item label="任务附件" prop="cate">
              <uploader
                :files="taskData.taskAttaches"
                :canUpload="false"
                @onDownload="handleTaskAttachDownload"
                width="80px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="执行方式" prop="cate">
              <el-select
                v-model="executeType"
                placeholder="请选择执行方式"
                @change="onExecuteTypeChange"
              >
                <el-option :key="1" label="执行预案" :value="1" />
                <el-option :key="2" label="指派任务" :value="2" />
                <el-option :key="3" label="立即执行" :value="3" />
                <el-option :key="4" label="终止任务" :value="4" />
              </el-select>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-search"
                :style="{ marginLeft: '15px' }"
                @click="handleSearchDoc"
                >搜索知识库相关文档
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="executeType == 1">
          <el-row :gutter="15">
            <el-col :span="24">
              <el-form-item label="预案" prop="event_name">
                <span :style="{ marginRight: '15px' }" v-if="planId != 0">{{
                  planTitle
                }}</span>
                <el-button type="primary" size="mini" @click="handlePickPlan"
                  >选择预案</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="响应级别" prop="event_name">
                <el-select
                  v-model="responseLevel"
                  placeholder="请选择响应级别"
                  :style="{ width: '10  0%' }"
                >
                  <el-option
                    key="0"
                    label="请先选择预案"
                    :value="0"
                    v-if="planId == 0"
                  />
                  <el-option
                    v-for="item in responseLevelOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-form-item label="执行人" prop="dept">
                <span :style="{ marginRight: '15px' }" v-if="userId != 0">{{
                  nickName
                }}</span>
                <el-button type="primary" size="mini" @click="handlePickStaff"
                  >选择执行人</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-if="executeType == 2">
          <el-form-item label="处置任务" prop="event_name">
            <el-row>
              <el-button type="primary" size="mini" @click="handleDrillTaskAdd"
                >添加处置任务</el-button
              >
            </el-row>
            <el-table
              :data="newTasks"
              size="mini"
              border
              :style="{ width: '100%', marginTop: '15px' }"
            >
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <div class="task-report">
                    <el-form
                      label-position="left"
                      class="demo-table-expand"
                      label-width="100px"
                    >
                      <template v-if="scope.row.status == 2">
                        <el-row>
                          <el-col :span="24">
                            <el-form-item label="任务反馈">
                              <span>{{ scope.row.submitContent }}</span>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row>
                          <el-col :span="12">
                            <el-form-item label="反馈文件">
                              <el-button
                                type="text"
                                @click="handleTaskReportAttach(scope.row)"
                                >查看任务反馈文件>></el-button
                              >
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="反馈时间">
                              {{ scope.row.submitTime }}
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </template>
                      <template v-else>
                        <el-row>
                          <el-col :span="24">
                            <el-form-item label="任务反馈">
                              <span>任务未完成</span>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </template>
                    </el-form>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="执行人" width="180">
              </el-table-column>
              <el-table-column prop="deptName" label="所属部门" width="180">
              </el-table-column>
              <el-table-column prop="taskContent" label="任务内容">
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
        <template v-if="executeType == 3">
          <el-row>
            <el-col :span="24">
              <el-form-item label="反馈内容" prop="countText">
                <el-row>
                  <template v-if="!isRadioInputing">
                    <el-button
                      type="success"
                      icon="el-icon-video-play"
                      size="mini"
                      @click="handleStartRadioInput"
                      >启动语音录入</el-button
                    >
                  </template>
                  <template v-if="isRadioInputing">
                    <el-button
                      type="warning"
                      icon="el-icon-video-pause"
                      size="mini"
                      @click="handleStopRadioInput"
                      >停止语音录入</el-button
                    >
                  </template>
                </el-row>
                <el-row :style="{ marginTop: '10px' }">
                  <el-input
                    type="textarea"
                    v-model="formData.content"
                    :disabled="disabled"
                    placeholder="请输入反馈内容"
                  >
                  </el-input>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="反馈附件" prop="countText">
                <uploAding
                  @uploading="getMsgFormSon"
                  :hidden="hidden"
                ></uploAding>
                <el-table :data="uploadinglist" max-height="250">
                  <el-table-column
                    prop="attachname"
                    label="名称"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="attachsize"
                    label="大小"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="attachtype"
                    label="类型"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="remove(scope.$index)"
                        v-if="hidden == false"
                      >
                        移除
                      </el-button>
                      <el-button
                        type="text"
                        size="small"
                        @click="downloadFile(scope.row)"
                      >
                        下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-if="executeType == 4">
          <el-row>
            <el-col :span="24">
              <el-form-item label="终止原因" prop="countText">
                <el-input
                  type="textarea"
                  v-model="formData.reason"
                  :disabled="disabled"
                  placeholder="请输入终止原因"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row :gutter="15" v-if="executeType == 1">
          <el-col :span="24">
            <el-form-item label="转发消息" prop="dept">
              <el-button
                type="primary"
                size="mini"
                @click="handleSysMessagePick"
                >选择我的消息</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15" v-if="messageId > 0">
          <el-col :span="24">
            <el-form-item label="" prop="dept">
              转发消息内容：{{ messageContent }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="handleSubmitTask">处置完成</el-button>
      </div>
      <plan-picker ref="planPicker" @handleOk="onPlanSelected" />
      <handle-task-edit
        ref="handleTaskEdit"
        :taskType="taskData != null && taskData.type == 2 ? 'handle' : 'drill'"
        @handleOk="onDrillTaskSave"
      />
      <staff-choose-dialog
        ref="staffChooseDialog"
        :muilt="false"
        @Unitpersonnel="onStaffChoose"
      />
      <task-report-attach ref="taskReportAttach" />
      <drill-role-picker ref="drillRolePicker" @handleOk="onRoleSelected" />
      <message-picker ref="messagePicker" @handleOk="onMessageSelected" />
    </el-dialog>
    <doc-search ref="docSearchDialog" />
  </div>
</template>

<script>
import uploAding from "../../components/uploAding/index.vue";
import dialogMixin from "../../../mixins/dialogMixin";
import PlanPicker from "@/views/components/planPicker/index.vue";
import HandleTaskEdit from "@/views/components/taskEditView/taskEdit.vue";
import StaffChooseDialog from "@/views/components/staffChooseDialog/index.vue";
import * as HandleApi from "@/api/response/handle.js";
import TaskReportAttach from "@/views/response/handle/components/TaskReportAttach.vue";
import * as DrillApi from "@/api/drill/drill.js";
import DrillRolePicker from "@/views/components/drillRolePicker/index.vue";
import MessagePicker from "./MessagePicker.vue";
import Uploader from "@/views/components/uploader/index.vue";
import DocSearch from "@/views/components/docSearch/DocSearch.vue";
import radioInputMixin from "../../../mixins/radioInputMixin";
export default {
  name: "TaskExecuteDialog",
  mixins: [dialogMixin, radioInputMixin],
  components: {
    uploAding,
    PlanPicker,
    HandleTaskEdit,
    StaffChooseDialog,
    TaskReportAttach,
    DrillRolePicker,
    MessagePicker,
    Uploader,
    DocSearch,
  },
  props: {
    handClick: {
      type: Function,
    },
  },
  data() {
    return {
      title: "执行任务",
      open: false,
      taskData: null,
      formData: {
        content: "",
        taskAttaches: [],
      },
      uploadinglist: [],
      countText: "",
      status: 2,
      disabled: false,
      hidden: false,
      //预案任务提交
      type: 2,
      //详情
      flag: "",
      meettype: "",
      executeType: 1,
      currentGroup: {
        flowId: 1,
        flowTitle: "组建领导小组",
        roleList: [
          {
            deptId: 0,
            userName: "测试",
          },
          {
            deptId: 0,
            userName: "测试",
          },
        ],
      },
      responseLevels: [
        {
          label: "Ⅰ级响应",
          value: 1,
        },
        {
          label: "Ⅱ级响应",
          value: 2,
        },
        {
          label: "Ⅲ级响应",
          value: 3,
        },
        {
          label: "Ⅳ级响应",
          value: 4,
        },
      ],
      planTitle: "",
      planId: 0,
      responseLevel: 0,
      nickName: "",
      newTasks: [],
      responseLevelOption: [],
      userId: 0,
      nickName: "",
      groups: [],
      messageId: 0,
      messageContent: "",
      isRadioInputing: false,
      recResultArr: [],
    };
  },
  mounted() {
    this.initRadioWs(
      (change) => {
        console.log(change, "change");
        if (this.recResultArr.length > 1) {
          this.recResultArr[1] = change.result.voice_text_str;
        } else {
          this.recResultArr[0] = change.result.voice_text_str;
        }
        this.formData.content = this.recResultArr.join(" ");
      },
      (end) => {
        console.log(end, "end");
        this.recResultArr[0] = this.recResultArr.join(" ");
        if (this.recResultArr.length == 1) {
          this.recResultArr.push("");
        } else {
          this.recResultArr[1] = "";
        }
        this.formData.content = this.recResultArr[0];
      },
      (stop) => {
        console.log(stop, "stop");
      }
    );
  },
  provide() {
    return {
      groups: () => this.groups,
    };
  },
  computed: {
    dialogWidth() {
      if (this.executeType == 1) {
        return "600px";
      }
      if (this.executeType == 2) {
        return "80%";
      }
      return "60%";
    },
  },
  methods: {
    //完成任务调
    showDialog(data) {
      console.log(data);
      this.taskData = data;
      // 如果是演练计划，提前获取演练计划的角色人员数据
      if (data.type == 1) {
        this.getDrillGroupRoles();
      }
      this.open = true;
    },
    getDrillGroupRoles() {
      DrillApi.getDrillGroupRole(this.taskData.handleId).then((res) => {
        this.groups = res.data;
      });
    },
    handlePickPlan() {
      this.$refs.planPicker.showDialog();
    },
    onPlanSelected(data) {
      this.planId = data.planId;
      this.planTitle = data.planName;
      this.responseLevel = 0;
      let levels = data.responseLevel.split(",").map(Number);
      levels.forEach((l) => {
        this.responseLevelOption.push(
          this.responseLevels.find((val) => val.value == l)
        );
      });
    },
    handleDrillTaskAdd() {
      this.$refs.handleTaskEdit.add();
    },
    onDrillTaskSave(data) {
      HandleApi.handleTaskSet({
        taskId: data.taskId,
        parentId: this.taskData.taskId,
        handleId: this.taskData.handleId,
        levelId: this.taskData.levelId,
        groupId: data.groupId,
        receiveUser: data.userId,
        taskContent: data.taskContent,
        messageId: data.messageId,
      }).then((res) => {
        this.$modal.msgSuccess("处置任务编辑成功");
        this.getNewTaskList();
      });
    },
    async getNewTaskList() {
      HandleApi.getHandleTasksList({ taskId: this.taskData.taskId }).then(
        (res) => {
          this.newTasks = res.data;
        }
      );
    },
    handlePickStaff() {
      if (this.taskData.type == 2) {
        // 处置任务，从全局选人
        this.$refs.staffChooseDialog.showDialog("选择执行人");
      } else {
        // 演练任务，根据演练计划配置的角色选人
        this.$refs.drillRolePicker.showDialog();
      }
    },
    onStaffSelected(data) {},
    onExecuteTypeChange() {
      if (this.executeType == 2) {
        this.getNewTaskList();
      }
      this.messageId = 0;
      this.messageContent = "";
    },
    handleSubmitTask() {
      switch (this.executeType) {
        case 1:
          //执行预案
          this.executePlan();
          break;
        case 2:
          //指派任务
          this.sendNewTask();
          break;
        case 3:
          // 立即执行
          this.executeTask();
          break;
        case 4:
          // 终止执行
          this.stopExecuteTask();
          break;
      }
    },
    executePlan() {
      // 提交执行预案
      let data = {};
      data.taskId = this.taskData.taskId;
      data.executeType = 1;
      data.planId = this.planId;
      data.responseLevel = this.responseLevel;
      data.executeUserId = this.userId;
      data.status = 2;
      data.messageId = this.messageId;
      HandleApi.handleSubmitTask(data).then((res) => {
        this.$modal.msgSuccess("任务提交成功");
        this.open = false;
        this.$emit("handleOk");
      });
    },
    sendNewTask() {
      //提交指派任务
      if (this.newTasks.length == 0) {
        this.$modal.msgError("未指派任务，无法完成当前任务");
        return false;
      }
      let data = {};
      data.taskId = this.taskData.taskId;
      data.executeType = 2;
      data.status = 2;
      HandleApi.handleSubmitTask(data).then((res) => {
        this.$modal.msgSuccess("任务提交成功");
        this.open = false;
        this.$emit("handleOk");
      });
    },
    executeTask() {
      // 立即执行任务提交
      let data = {};
      data.taskId = this.taskData.taskId;
      data.taskContent = this.formData.content;
      let attachIds = [];
      this.uploadinglist.forEach((a) => {
        attachIds.push(a.attachid);
      });
      data.attachIds = attachIds.join(",");
      data.executeType = 4;
      data.status = 2;
      HandleApi.handleSubmitTask(data).then((res) => {
        this.$modal.msgSuccess("任务执行成功");
        this.open = false;
        this.$emit("handleOk");
      });
    },
    stopExecuteTask() {
      // 终止执行任务
      let data = {};
      data.taskId = this.taskData.taskId;
      data.taskContent = this.formData.reason;
      data.executeType = 3;
      data.status = 3;
      HandleApi.handleSubmitTask(data).then((res) => {
        this.$modal.msgSuccess("任务终止成功");
        this.open = false;
        this.$emit("handleOk");
      });
    },
    onStaffChoose(deptId, userId, user, dept) {
      console.log(deptId, userId, user, dept);
      this.userId = userId;
      this.nickName = user.nickName;
    },
    //上传
    getMsgFormSon(data) {
      this.uploadinglist.push(data);
    },
    //移除
    remove(index) {
      this.uploadinglist.splice(index, 1);
    },
    downloadFile(row) {
      this.download(
        `com/ComAttach/download/${row.attachid}`,
        {},
        `${row.attachname}.${row.attachtype}`
      );
    },
    handleTaskReportAttach(data) {
      this.$refs.taskReportAttach.showDialog(data.taskId);
    },
    onRoleSelected(data) {
      this.userId = data.roleId;
      this.nickName = data.roleName;
    },
    handleSysMessagePick() {
      this.$refs.messagePicker.showDialog();
    },
    onMessageSelected(data) {
      // 选择了消息
      this.messageId = data.messageId;
      this.messageContent = data.message;
    },
    handleTaskAttachDownload(row) {
      // 下载附件
      this.download(
        `com/ComAttach/download/${row.attachid}`,
        {},
        `${row.attachname}.${row.attachtype}`
      );
    },
    handleSearchDoc() {
      this.$refs.docSearchDialog.show();
    },
    handleStartRadioInput() {
      if (this.formData.content == "") {
        this.recResultArr = [];
      } else {
        this.recResultArr = [this.formData.content, ""];
      }
      this.startRecord();
      this.isRadioInputing = true;
    },
    handleStopRadioInput() {
      this.stopRecord();
      this.isRadioInputing = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.task-report {
  padding: 0 20px 20px;
}
</style>
